﻿using System;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Complaint.Binders;
using Complaint.Common;

namespace Complaint
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Root",
                "",
                new { controller = "Home", action = "Index" },
                new[] { "Complaint.Controllers" }
            );

            routes.MapRoute(
                "ComplaintByUser",
                "Complaint/ByUser/{userName}",
                new { controller = "Complaint", action = "SearchByUser", userName = "" },
                new[] { "Complaint.Controllers" }
            );

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" },  // Parameter defaults
                new [] { "Complaint.Controllers" }
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);
            ModelBinders.Binders[typeof(DateTime)] = new DateTimeModelBinder();  
            Application["PageSize"] = ConfigHelper.GetConfigValueAsInt("PageSize");
        }

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                string[] roles = authTicket.UserData.Split(new[] { ',' });
                var userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles);
                Context.User = userPrincipal;
            }
        }

        protected void Application_AuthorizeRequest(Object sender, EventArgs e)
        {
            if (Request.UrlReferrer == null) return;
            if (Request.Path.ToUpper().EndsWith("ACCOUNT/LOGON")
                && Request.UrlReferrer.AbsolutePath.ToUpper().EndsWith("ACCOUNT/LOGON")
                && Request.UrlReferrer.Query.Contains("%2fAdmin")
                && Request.IsAuthenticated)
            {
                Response.Redirect("~/Error/NoAccess");
            }
        }
    }
}